package com.xiliu.server.modules.become.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiliu.common.constant.WxConstants;
import com.xiliu.common.utils.StringUtils;
import com.xiliu.server.modules.app.vo.BecomeVo;
import com.xiliu.server.modules.become.entity.XlBecome;
import com.xiliu.server.modules.become.entity.XlBecomeItem;
import com.xiliu.server.modules.become.mapper.XlBecomeMapper;
import com.xiliu.server.modules.become.service.IXlBecomeItemService;
import com.xiliu.server.modules.become.service.IXlBecomeService;
import com.xiliu.server.modules.ucenter.entity.XlUser;
import com.xiliu.server.modules.ucenter.service.XlUserService;
import com.xiliu.server.modules.wxmsg.entity.XlWxTemplateMsg;
import com.xiliu.server.modules.wxmsg.service.IXlWxTemplateMsgService;
import com.xiliu.server.modules.wxmsg.service.SendTemplateMsgService;
import com.xiliu.server.modules.wxmsg.vo.WxMsgVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 房管员认证表Service业务层处理
 * 
 * @author xiliu
 * @date 2022-12-30
 */
@Service
public class XlBecomeServiceImpl extends ServiceImpl<XlBecomeMapper, XlBecome> implements IXlBecomeService {

    @Autowired
    private IXlBecomeItemService becomeItemService;
    @Autowired
    private XlUserService userService;
    @Autowired
    private IXlWxTemplateMsgService wxTemplateMsgService;
    @Autowired
    private SendTemplateMsgService sendtemplateMsgService;

    @Override
    public XlBecome selectXlBecomeByComeId(Long comeId) {
        XlBecome xlBecome = baseMapper.selectXlBecomeByComeId(comeId);
        if (xlBecome != null ) {
            if (StringUtils.isNotBlank(xlBecome.getImg())) {
                xlBecome.setImgUrl(Arrays.asList(xlBecome.getImg().split(",")));
            }
            if (xlBecome.getLevel() == 2) {
                List<XlBecomeItem> items = becomeItemService.list(new LambdaQueryWrapper<XlBecomeItem>().eq(XlBecomeItem::getBecomeId,comeId));
                if (CollectionUtil.isNotEmpty(items)) {
                    for (XlBecomeItem item : items) {
                        item.setImgUrl(Arrays.asList(item.getImg().split(",")));
                    }
                }
                xlBecome.setHouse(items);
            }
        }
        return xlBecome;
    }

    @Override
    public boolean creatBecome(BecomeVo becomeVo) {
        XlBecome become = new XlBecome();
        BeanUtils.copyProperties(becomeVo, become);
        become.setBecomeDate(new Date());
        become.setState(Long.parseLong("1"));
        become.setResult(becomeVo.getLevel() == 2 ? "房东" : "房管员");
        List<BecomeVo.ImageVo> imageVoList = becomeVo.getImgs();
        become.setImg(String.join(",",imageVoList.stream().map(v -> v.getUrl()).collect(Collectors.toList())));
        boolean result = this.save(become);
        if (CollectionUtil.isNotEmpty(becomeVo.getHouse())) {
            for (XlBecomeItem item : becomeVo.getHouse()) {
                XlBecomeItem newItem = new XlBecomeItem();
                BeanUtils.copyProperties(item, newItem);
                newItem.setBecomeId(become.getBecomeId());
                newItem.setImg(String.join(",",item.getImgs().stream().map(v -> v.getUrl()).collect(Collectors.toList())));
                result = becomeItemService.save(newItem);
            }
        }
        // 给用户发送一条订阅消息
        XlUser user = userService.getById(becomeVo.getUserid());
        WxMsgVo vo = this.convertWxMsgVo(user.getOpenId(), WxConstants.HYRZ,null,becomeVo);
        sendtemplateMsgService.sendWxappTemplate(vo);
        //TODO 给平台消息接收员也送一条公众号模板消息
        return result;
    }

    @Override
    public List<XlBecome> selectXlBecomeList(XlBecome xlBecome) {
        return baseMapper.selectXlBecomeList(xlBecome);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteByBecomeIds(Long[] becomeIds) {
       int num = baseMapper.deleteBatchIds(Arrays.asList(becomeIds));
        List<XlBecomeItem> itemList = becomeItemService.list(new LambdaQueryWrapper<XlBecomeItem>()
                .in(XlBecomeItem::getBecomeId,Arrays.asList(becomeIds)));
        if (CollectionUtil.isNotEmpty(itemList)) {
            becomeItemService.removeBatchByIds(itemList);
        }
        return num;
    }

    /**
     * 组装消息模板内容
     **/
    private String convertWxMsgVoData(BecomeVo becomeVo) {
        JSONObject object = new JSONObject();
        object.put("thing2", becomeVo.getName());
        object.put("thing4", becomeVo.getLevel() == 2 ? "房东" : "房管员");
        object.put("time3", DateUtil.format(new Date(), "yyyy年MM月dd日"));
        object.put("thing6", "申请己提交，我们将尽快为您审核。");
        return String.valueOf(object);
    }
    /**
     * 组装平台消息模板内容
     **/
    private String convertAdminData(String title) {
        JSONObject object = new JSONObject();
        object.put("thing2", "收到1条个人用户发布的消息，请登录后台查看！");
        object.put("thing4", title);
        object.put("time3", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        object.put("thing6", "");
        return String.valueOf(object);
    }
    /**
     * 组装消息内容
     **/
    private WxMsgVo convertWxMsgVo(String openId,String msgType,String title, BecomeVo becomeVo) {
        WxMsgVo vo = new WxMsgVo();
        // 查询模板id
        XlWxTemplateMsg wxTemplateMsg = wxTemplateMsgService.getOne(new LambdaQueryWrapper<XlWxTemplateMsg>().eq(XlWxTemplateMsg::getBelongType, msgType),false);
        vo.setTouser(openId);
        vo.setTemplateId(wxTemplateMsg.getTemplateId());
        vo.setPage(wxTemplateMsg.getPageUrl());
        if (WxConstants.MSG_ADMIN.equals(msgType)) {
            vo.setData(this.convertAdminData(title));
        } else {
            vo.setData(this.convertWxMsgVoData(becomeVo));
        }
        return vo;
    }
}
